package dlg.code.producer.s2;

import dlg.code.producer.ItemBuffer;

import java.util.concurrent.TimeUnit;

public class TakeThread implements Runnable{

    private final ItemBuffer itemBuffer;
    public TakeThread(ItemBuffer itemBuffer) {
        this.itemBuffer = itemBuffer;
    }

    @Override
    public void run() {
        while (true){
            itemBuffer.lock.lock();
            while (itemBuffer.isEmpty()) {
                System.out.println(Thread.currentThread().getName() + " waiting");
                try {
                    itemBuffer.notEmpty.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            String take = itemBuffer.take();
            System.out.println(Thread.currentThread().getName() + " take = " + take);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            itemBuffer.notFull.signalAll();
            itemBuffer.lock.unlock();
        }
    }
}
